package com.sky.controller.admin;

import com.sky.annotation.AutoFill;import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Validated // ⬅️ 加上这个注解才能让 GET 请求中的 @Valid 生效
@Tag(name = "员工管理")
public class EmployeeController {
    // 注入 Validator
    @Autowired
    private Validator validator;

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        // 登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder().id(employee.getId()).userName(employee.getUsername()).name(employee.getName()).token(token).build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    @Operation(summary = "员工退出")
    public Result<String> logout() {
        return Result.success();
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     * @return
     */
    @PostMapping
    @Operation(summary = "新增员工")
    public Result save(@RequestBody EmployeeDTO employeeDTO) {
        log.info("新增员工，员工数据：{}", employeeDTO);
        System.out.println("当前线程的id:" + Thread.currentThread().getId());
        Integer count = employeeService.save(employeeDTO);
        if (count > 0) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }

    }

    /**
     * 根据员工姓名分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @Operation(summary = "根据员工姓名分页查询")
    public Result<PageResult> page(@Valid EmployeePageQueryDTO employeePageQueryDTO) {
        log.info("分页查询：{}", employeePageQueryDTO);
        PageResult<Employee> pageResult = employeeService.EmpPage(employeePageQueryDTO);
        if (ObjectUtils.isNotEmpty(pageResult)) {
            return Result.success(pageResult);
        }else{
            return Result.error("查询失败");
        }
    }

    /**
     * 根据id启用、禁用员工账号
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @Operation(summary = "启用、禁用员工账号")
    public Result updStatus (@PathVariable Integer status, Integer id) {
        log.info("员工状态：{},员工id：{}", status,id);
        HashMap<String, Object> empMap = new HashMap<>();
        empMap.put("status",status);
        empMap.put("id",id);
        Integer count = employeeService.updStatus(empMap);
        if (count > 0){
            return Result.success();
        }else {
            return Result.error("操作失败");
        }

    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据id查询员工信息")
    public Result<Employee> getById(@PathVariable Integer id) {
        log.info("根据id查询员工信息：{}", id);
        Employee employee = employeeService.getById(id);
        if (ObjectUtils.isNotEmpty(employee)){
            return Result.success(employee);
        }else {
            return Result.error("查询失败");
        }
    }

    /**
     * 编辑员工信息
     * @param employeeDTO
     * @return
     */
    @PutMapping
    @Operation(description = "编辑员工信息")
    @AutoFill(value = OperationType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    public Result update(@RequestBody EmployeeDTO employeeDTO) {
        log.info("员工信息：{}", employeeDTO);
        Integer count = employeeService.update(employeeDTO);
        if (count > 0) {
            return Result.success();
        } else {
            return Result.error("编辑失败");
        }
    }

}
